﻿using Kingdee.BOS;
using Kingdee.BOS.App.Core;
using Kingdee.BOS.Core.Bill;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.Metadata.ConvertElement.PlugIn;
using Kingdee.BOS.Core.Metadata.ConvertElement.PlugIn.Args;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Core.Metadata.FieldElement;
using Kingdee.BOS.Core.SqlBuilder;
using Kingdee.BOS.Orm;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Kingdee.BOS.Web.Bill;
using Kingdee.K3.Core.MFG.EntityHelper;
using Kingdee.K3.Core.SCM;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RK.Dz_ConvertBill.Ronma
{
    [Description("自定义单据转换_润马_生产超耗申请到补料、退货通知单--销售退货单"), HotUpdate]
    public class ConvertBill : AbstractConvertPlugIn
    {
        string srcEntryId = "";
        string entryForm = "";
        public override void AfterConvert(AfterConvertEventArgs e)
        {
            base.AfterConvert(e);
            SetInfos(e.SourceBusinessInfo.GetForm().Id, e.TargetBusinessInfo.GetForm().Id);
            if (!this.Option.GetVariables().ContainsKey("MESParamters"))
            {
                return;
            }
            Dictionary<string, object> mesDic = this.Option.GetVariables()["MESParamters"] as Dictionary<string, object>;
            var tArray = e.Result.FindByEntityKey("FBillHead");
            IBillView billView = CreateBillView.CreateView(this.Context, e.TargetBusinessInfo.GetForm().Id);
            foreach (var tArr in tArray)
            {
                billView.Model.DataObject = tArr.DataEntity;
                DifyModel(billView, mesDic);
                Entity entity = billView.BusinessInfo.GetEntity("FEntity");
                FlexSaveService saveService = new FlexSaveService(this.Context, "Save");
                saveService.BatchSaveEntityFlexObject(billView.BusinessInfo, entity, (DynamicObject[])(object)new DynamicObject[1]
                {
                    tArr.DataEntity
                });
            }
        }

        private void SetInfos(string sourceId, string targetId)
        {
            if (sourceId.EqualsIgnoreCase("YCVN_SCBLD") && targetId.EqualsIgnoreCase("PRD_FeedMtrl"))
            {
                srcEntryId = "ReqEntryId";
                entryForm = "Entity";
            }
            if (sourceId.EqualsIgnoreCase("SAL_RETURNNOTICE") && targetId.EqualsIgnoreCase("SAL_RETURNSTOCK"))
            {
                srcEntryId = "THSrcEntryId";
                entryForm = "SAL_RETURNSTOCKENTRY";
            }
        }

        private void DifyModel(IBillView billView, Dictionary<string, object> mesDic)
        {
            if (mesDic.ContainsKey("FBillHead") && (mesDic["FBillHead"] as Dictionary<string, object>).Count > 0)
            {
                foreach (var item in mesDic["FBillHead"] as Dictionary<string, object>)
                {
                    billView.Model.SetValue(item.Key, Convert.ToString(item.Value), 0);
                    billView.InvokeFieldUpdateService(item.Key, 0);
                }
            }

            var eRows = billView.Model.DataObject[entryForm] as DynamicObjectCollection;
            RelatedFlexGroupField val5 = billView.BusinessInfo.GetField("FAuxPropId") as RelatedFlexGroupField;
            if (mesDic.ContainsKey("FEntity") && (mesDic["FEntity"] as Dictionary<string, object>).Count > 0)
            {
                int rowCount = eRows.Count;
                int oldIndex = eRows.Count;
                for (int i = 0; i < rowCount; i++)
                {
                    var rowsDic = mesDic["FEntity"] as Dictionary<string, object>;
                    var ReqEntryId = Convert.ToString(eRows[i][srcEntryId]);
                    if (!rowsDic.ContainsKey(ReqEntryId))
                    {
                        continue;
                    }
                    var wmsRows = rowsDic[ReqEntryId] as Dictionary<string, object>;
                    for (int j = 0; j < wmsRows.Count; j++)
                    {
                        var mesRow = wmsRows[j.ToString()] as Dictionary<string, object>;
                        int newIndex;
                        if (j > 0)
                        {
                            AssociatedCopyRowUtil.CopyRow(billView, "FEntity", i, oldIndex, true);
                            newIndex = oldIndex;
                            oldIndex++;
                        }
                        else
                        {
                            newIndex = i;
                        }
                        
                        foreach (var row in mesRow)
                        {
                            if (row.Value is Dictionary<string, object>)
                            {
                                var fzzx = row.Value as Dictionary<string, object>;
                                if (row.Key == "FAuxPropId")
                                {
                                    SetFzzx(val5, eRows, newIndex, fzzx, billView, row);
                                }
                                else if (fzzx.ContainsKey("FNumber") && row.Key != "FMaterialId" && !fzzx["FNumber"].IsNullOrEmptyOrWhiteSpace())
                                {
                                    billView.Model.SetEntryCurrentRowIndex("FEntity", newIndex);
                                    billView.Model.SetItemValueByNumber(row.Key, fzzx["FNumber"].ToString(), newIndex);
                                    
                                    billView.InvokeFieldUpdateService(row.Key, newIndex);
                                }
                            }
                            else
                            {
                                if (!row.Value.IsNullOrEmptyOrWhiteSpace())
                                {
                                    billView.Model.SetEntryCurrentRowIndex("FEntity", newIndex);
                                    billView.Model.SetValue(row.Key, row.Value, newIndex);
                                    //InvokeFieldUpdateService方法，如果值没有变化，就不会生效
                                    billView.InvokeFieldUpdateService(row.Key, newIndex);
                                }
                            }
                        }
                    }
                }
            }
        }

        private void SetFzzx(RelatedFlexGroupField val5, DynamicObjectCollection eRows, int newIndex, Dictionary<string, object> fzzx, IBillView billView, KeyValuePair<string, object> row)
        {
            DynamicObject val6 = new DynamicObject(val5.RefFormDynamicObjectType);
            val5.RefIDDynamicProperty.SetValue(eRows[newIndex], 0);
            val5.DynamicProperty.SetValue(eRows[newIndex], val6);
            foreach (var zx in fzzx)
            {
                if (!zx.Value.IsNullOrEmptyOrWhiteSpace())
                {
                    Field field = val5.RelateFlexBusinessInfo.GetField(zx.Key);
                    if (field is BaseDataField)
                    {
                        BaseDataField val7 = field as BaseDataField;
                        DynamicObject dynamicObjectByFormIdAndId = GetDynamicObjectByFormIdAndId(this.Context, "BOS_ASSISTANTDATA_DETAIL", null, "FNumber = '" + zx.Value?.ToString() + "'");
                        if (dynamicObjectByFormIdAndId.IsNullOrEmptyOrWhiteSpace())
                        {
                            throw new KDException("ErrorCode", "请求的辅助属性不存在：" + zx.Value?.ToString());
                        }
                        var array3 = BusinessDataServiceHelper.LoadFromCache(this.Context, new object[1] { dynamicObjectByFormIdAndId["id"] }, val7.RefFormDynamicObjectType);
                        val7.RefIDDynamicProperty.SetValue(val6, dynamicObjectByFormIdAndId["id"]);
                        val7.DynamicProperty.SetValue(val6, array3[0]);
                    }
                    else
                    {
                        field.DynamicProperty.SetValue(val6, zx.Value);
                    }
                }
            }
            billView.InvokeFieldUpdateService(row.Key, newIndex);
        }

        private DynamicObject GetDynamicObjectByFormIdAndId(Context context, string formId, object orgNumber, string where)
        {
            DynamicObject result = null;
            FormMetadata formMetaData = MetaDataServiceHelper.GetFormMetaData(context, formId);
            QueryBuilderParemeter val = new QueryBuilderParemeter
            {
                FormId = formId
            };
            List<string> list = new List<string>();
            if (formMetaData.BusinessInfo.MainOrgField != null)
            {
                list.Add($" {formMetaData.BusinessInfo.MainOrgField.Key}.Fnumber='{orgNumber}' ");
            }
            if (!where.IsNullOrEmptyOrWhiteSpace())
            {
                list.Add(where);
            }
            val.FilterClauseWihtKey = (string.Join(" and ", list));
            DynamicObject[] array = BusinessDataServiceHelper.Load(context, formMetaData.BusinessInfo.GetDynamicObjectType(), val);
            if (array.Length != 0)
            {
                result = array.FirstOrDefault();
            }
            return result;
        }
    }
}
